import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/cart'
export default {
  namespaced: true,
  state() {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList(state, payload) {
      state.cartList = payload
      // console.log(state.cartList)
    }
  },
  actions: {
    async asyncSetCartList(context, payload) {
      await insertCart(payload)
      const res = await findCartList()
      console.log(res)
      context.commit('setCartList', res.result)
    },
    // 删除购物车
    async asyncDelCart(context, skuIds) {
      await deleteCart(skuIds)
      const res = await findCartList()
      context.commit('setCartList', res.result)
    },
    // 更新购物车
    async asyncUpdate(context) {
      const res = await findCartList()
      context.commit('setCartList', res.result)
    },
    // 更新购物车的单选中状态
    async asyncSingleCheck(context, goods) {
      await updateCart(goods)
      const res = await findCartList()
      context.commit('setCartList', res.result)
    },
    // 购物车全选状态
    async asyncAllCheck(context, selected) {
      const ids = context.state.cartList.map(it => it.skuId)
      await checkAllCart({ selected, ids })

      // 更新购物车数据
      const res = await findCartList()
      // 3. 更新state
      context.commit('setCartList', res.result)
    },
    // 更新购物车数量
    async asyncChangeCount(context, goods) {
      await updateCart(goods)
      const res = await findCartList()
      context.commit('setCartList', res.result)
    }
  },
  getters: {
    allCount(state) {
      // let total = 0
      // state.cartList.forEach(item => {
      //   total += item.count
      // })
      // return total
      const total = state.cartList.reduce((acc, cuu) => {
        return acc + cuu.count
      }, 0)
      return total
    },
    allPrice(state) {
      let total = 0
      state.cartList.forEach(item => {
        total += item.count * item.price
      })
      return total
    },
    // 选中数量
    selectedCount(state) {
      return state.cartList.filter(item => item.selected).reduce((acc, cur) => {
        return acc + cur.count
      }, 0)
    },
    // 选中的价格
    selectedPrice(state) {
      return state.cartList.filter(item => item.selected).reduce((acc, cur) => {
        return acc + cur.count * cur.price
      }, 0)
    }
  }
}
